# -*- coding: utf-8 -*-
#
# Copyright (c) 2011,2012 RMIT e-Research Office
#   (RMIT University, Australia)
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#    *  Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#    *  Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#    *  Neither the name of RMIT University nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

"""
Ingests records from the AFIRC repository into SMRA

.. moduleauthor:: Ian Thomas <Ian.Edward.Thomas@rmit.edu.au>
"""
import logging
from os import path
from django.contrib import admin
from django.utils.text import truncate_words

from smra.smra_portal import models
from smra.smra_portal.models import ParameterName
from smra.smra_portal.models import MediaObjectParameterSet
from smra.smra_portal.models import MediaObjectParameter
from smra.smra_portal.models import VirtualCollectionParameterSet
from smra.smra_portal.models import VirtualCollectionParameter


logger = logging.getLogger(__name__)
    
class ParameterNameInlines(admin.TabularInline):
    model = models.ParameterName
    ordering = ["-ranking"]
    extra = 0
 
    
class MediaObjectParameterInlines(admin.TabularInline):
    model = models.MediaObjectParameter
    list_display = ('paramset', 'name','value')
    ordering = ['name']
    def queryset(self, request):
        query = models.MediaObjectParameter.objects.all()
        qs = super(MediaObjectParameterInlines,
                   self).queryset(request).filter(query)
        return qs

    
class MediaObjectParameterSetInlines(admin.TabularInline):
    model = models.MediaObjectParameterSet  
    ordering = ['-ranking']  
 
    
class SchemaAdmin(admin.ModelAdmin):
    inlines = [ParameterNameInlines]
    list_display = ( 'name','namespace','description')
    list_filter = ('name','namespace', 'description')
    ordering = ('-namespace','-name')
    search_fields = ('name','description')
    prepopulated_fields = {"name":("description",)}
    #  inlines = (MediaObjectParameterSetInlines,)

   
class MediaObjectAdmin(admin.ModelAdmin):
    list_display = ('description', 'repos')
    list_filter = ('repos',)
    ordering = ('-description',)
    search_fields = ('description',)
     
    inlines = (MediaObjectParameterSetInlines,)
    #filter_horizontal = ('schemas',)
    
#    def queryset(self, request):
#        qs = super(MediaObjectAdmin, self).queryset(request)
#        if not request.user.is_superuser:
#            qs = qs.filter(author=request.user)
#        return qs
#    pass
#    
    
class MediaObjectParameterAdmin(admin.ModelAdmin):
    
    def shorter_paramset(self,obj):
        return "%s" % (obj.paramset.media_object)
    shorter_paramset.short_description = 'Parameter Set'
    
    def shorter_name(self,obj):
        return "%s.%s" % (obj.paramset.schema.name,obj.name.name)
    shorter_name.short_description = 'Parameter Name'
    
    def shorter_value(self,obj):
        return "%s" % (truncate_words(obj.value,30))
    shorter_name.short_description = 'Parameter Value'
        
    list_display = ('shorter_paramset', 'shorter_name', 'shorter_value')    
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """ Populate the Parameter Name field based on the contents
        of the ParameterSet field.  This is a bit of hack, as its 
        all server side.  There may be a ajax solution"""        
        if db_field.name == "name":
            # use the PATH_INFO meta field to determine the pk for the
            # media object we are currently editing.  Dependent 
            # on the form of the url, which could be a problem.
            if 'PATH_INFO' in request.META:
                path_info = request.META['PATH_INFO']        
                _, pi = path.split(path_info[:-1])
                # parse the last element in the path
                if pi == 'add':
                    # This a new element, so go with complete list
                    kwargs["queryset"] = ParameterName.objects.all()       
                else:
                    # Extract the MediaObjectParameter primary key                                        
                    m = MediaObjectParameter.objects.get(pk=int(pi))
                    logger.debug("m = %s" % m)
                    
                    # get the primary key for the schema of current MOP
                    newpk = m.paramset.schema.pk
                    logger.debug("newpk = %s" % newpk)
                    # find all ParameterNames from schemas same as that 
                    # used in the current MOPS
                    kwargs["queryset"] = ParameterName.objects.filter(
                                                            schema__pk=newpk)
        return super(MediaObjectParameterAdmin, 
                     self).formfield_for_foreignkey(db_field, request, 
                                                    **kwargs)
    list_filter = ('name','paramset__schema','paramset__media_object')
    ordering = ('paramset__media_object', 'paramset__ranking',
                'paramset__name__ranking')
    search_fields = ('name',)
    fields = ('paramset', 'name', 'value')
    description = 'hello'

     
class VirtualCollectionParameterAdmin(admin.ModelAdmin):
    
    def shorter_paramset(self,obj):
        return "%s" % (obj.paramset.virt)
    shorter_paramset.short_description = 'Parameter Set'
    
    def shorter_name(self,obj):
        return "%s.%s" % (obj.paramset.schema.name,obj.name.name)
    shorter_name.short_description = 'Parameter Name'
    
    def shorter_value(self,obj):
        return "%s" % (truncate_words(obj.value,30))
    shorter_name.short_description = 'Parameter Value'
        
    list_display = ('shorter_paramset', 'shorter_name', 'shorter_value')    
    
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """ Populate the Parameter Name field based on the contents
        of the ParameterSet field.  This is a bit of hack, as its 
        all server side.  There may be a ajax solution"""        
        if db_field.name == "name":
            # use the PATH_INFO meta field to determine the pk for the
            # media object we are currently editing.  Dependent 
            # on the form of the url, which could be a problem.
            if 'PATH_INFO' in request.META:
                path_info = request.META['PATH_INFO']        
                _, pi = path.split(path_info[:-1])
                # parse the last element in the path
                if pi == 'add':
                    # This a new element, so go with complete list
                    kwargs["queryset"] = ParameterName.objects.all()       
                else:
                    # Extract the VirtualCollectionParameter primary key                                        
                    m = VirtualCollectionParameter.objects.get(pk=int(pi))
                    logger.debug("m = %s" % m)
                    
                    # get the primary key for the schema of current MOP
                    newpk = m.paramset.schema.pk
                    logger.debug("newpk = %s" % newpk)
                    # find all ParameterNames from schemas same as that 
                    # used in the current MOPS
                    kwargs["queryset"] = ParameterName.objects.filter(
                                                            schema__pk=newpk)
                              
        return super(VirtualCollectionParameterAdmin, 
                     self).formfield_for_foreignkey(db_field, request, 
                                                    **kwargs)
  
    list_filter = ('name','paramset__schema','paramset__virt')
    ordering = ('paramset__virt', 'paramset__ranking',
                'paramset__name__ranking')
    search_fields = ('name',)
    fields = ('paramset', 'name', 'value')
    description = 'hello'
    
class DeadLinkAdmin(admin.ModelAdmin):
    list_display = ('date_created', 'date_accessed','parameter','reason')
    ordering = ('date_created',)
    fields =  ('parameter','reason')
    

class VirtualCollectionParameterSetInlines(admin.TabularInline):
    model = models.VirtualCollectionParameterSet  
    ordering = ['-ranking']  
#   extra = 3
        

class VirtualCollectionAdmin(admin.ModelAdmin):
    list_display = ('name','owned_by','description',)
    list_filter = ('name',)
    ordering = ('-description',)
    search_fields = ('description',)
    inlines = (VirtualCollectionParameterSetInlines,)
    #filter_horizontal = ('schemas',)
    
#    def queryset(self, request):
#        qs = super(MediaObjectAdmin, self).queryset(request)
#        if not request.user.is_superuser:
#            qs = qs.filter(author=request.user)
#        return qs
#    pass
#    
    def queryset(self, request):
            qs = super(VirtualCollectionAdmin, self).queryset(request)
            if not request.user.is_superuser:
                qs = qs.filter(owned_by__user=request.user)
            return qs


admin.site.register(models.UserProfile)
admin.site.register(models.VirtualCollection,VirtualCollectionAdmin)
admin.site.register(models.System)
admin.site.register(models.Repository)
admin.site.register(models.MediaObject, MediaObjectAdmin)
admin.site.register(models.Schema, SchemaAdmin)
#admin.site.register(models.MediaObjectParameterSet)
#admin.site.register(models.ParameterName)
admin.site.register(models.MediaObjectParameter, MediaObjectParameterAdmin)
#admin.site.register(models.MediaObjectLinkList)
admin.site.register(models.DeadLink, DeadLinkAdmin)
admin.site.register(models.Key)
admin.site.register(models.Subquery)
admin.site.register(models.PartyRecord)
admin.site.register(models.ActivityRecord)
admin.site.register(models.VirtualCollectionParameterSet)
admin.site.register(models.VirtualCollectionParameter, 
                    VirtualCollectionParameterAdmin)
